package com.ojoin.trade.supplyloan_core.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.BufferedHeader;
import org.apache.http.protocol.HTTP;

import com.ojoin.trade.common.Constants;

public class JD {
	// The configuration items
	private static String userName = "jd_4d3791da589fb";
	private static String password = "JIURUNYUAN111111";

	private static String redirectURL = "http://vcp.jd.com/index/initIndexPage";
	private static String loginUrl = "https://vcp.jd.com/sub_reports/main";

	// Don't change the following URL
	private static String renRenLoginURL = "https://passport.jd.com/uc/loginService";

	// The HttpClient is used in one session
	private HttpResponse response;
	private DefaultHttpClient httpclient = new DefaultHttpClient();

	public Map<String, String> getParams() {
		Map<String, String> map = new HashMap<String, String>();
		String str = getText(loginUrl);
		String strs1[] = str.split("name=\"uuid\" value=\"");
		String strs2[] = strs1[1].split("\"/>");
		String uuid = strs2[0];
		map.put("uuid", uuid);
		System.out.println(strs2[0]);
		String str3s[] = strs1[1]
				.split("<input type=\"hidden\" name=\"");
		
		if (str3s == null || str3s.length == 0)
			return map;
		
		for(int i=0; i<str3s.length; i++) {
			if (i == 0)
				continue;
			String strs4[] = str3s[i].split("/>");
			String[] str4s = strs4[0].split("\"");
			if (strs4[0].indexOf("id") == -1) {
				String key = str4s[0];
				String value = str4s[2];
				if (key.equals("loginpwd"))
					continue;
				map.put(key, value);
			} else {
				String key = str4s[0];
				String value = str4s[4];
				if (key.equals("loginpwd"))
					continue;
				map.put(key, value);
			}
		}
		return map;
	}

	private boolean login() {
		Map map = getParams();

		HttpPost httpost = new HttpPost(renRenLoginURL);
		// All the parameters post to the web site
		List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
		nvps.add(new BasicNameValuePair("ReturnUrl", redirectURL));
		nvps.add(new BasicNameValuePair("loginname", userName));
		nvps.add(new BasicNameValuePair("nloginpwd", password));
		nvps.add(new BasicNameValuePair("loginpwd", password));
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next().toString();
			String value = map.get(key).toString();
			nvps.add(new BasicNameValuePair(key, value));

		}

		try {
			httpost.setEntity(new UrlEncodedFormEntity(
					(List<? extends org.apache.http.NameValuePair>) nvps,
					HTTP.UTF_8));
			response = httpclient.execute(httpost);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			httpost.abort();
		}
		return true;
	}

	private String getRedirectLocation() {
		BufferedHeader locationHeader = (BufferedHeader) response
				.getFirstHeader("Location");
		if (locationHeader == null) {
			return null;
		}
		return locationHeader.getValue();
	}

	private String getText(String redirectLocation) {
		HttpGet httpget = new HttpGet(redirectLocation);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = "";
		try {
			responseBody = httpclient.execute(httpget, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
			responseBody = null;
		} finally {
			httpget.abort();
			// httpclient.getConnectionManager().shutdown();
		}
		return responseBody;
	}

	public void printText() {
		if (login()) {
			System.out.println(getText(redirectURL));
			String redirectLocation = getRedirectLocation();
			if (redirectLocation != null) {
				System.out.println(getText(redirectLocation));
			}
		}
	}
	
	private void getPostData() throws Exception {
		String url = "http://vcp.jd.com/sub_procurement/procurement/orderList";
		String host = "vcp.jd.com";
		HttpClient httpClient = new HttpClient();
		httpClient.getHostConfiguration().setHost(host, 80, "http");

//		HttpMethod method = getMethod(url, param);
		HttpMethod method = purchaseOrderPostMethod(url);

		httpClient.executeMethod(method);

//		String response = method.getResponseBodyAsString();
//		BufferedReader reader = new BufferedReader(new InputStreamReader(
//				method.getResponseBodyAsStream()));
		System.out.println(method.getResponseBody().length);
		System.out.println(new String(method.getResponseBody(), Constants.ENCODING));
	}
	

	private HttpMethod purchaseOrderPostMethod(String url) throws IOException {
		PostMethod post = new PostMethod(url);
		post.setRequestHeader("Accept", "application/json, text/javascript, */*");
		post.setRequestHeader("Accept-Encoding", "gzip, deflate");
		post.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");
		post.setRequestHeader("Cache-Control", "no-cache");
		post.setRequestHeader("Connection", "keep-alive");
		post.setRequestHeader("Content-Length", "71");
		post.setRequestHeader("Cookie", "lighting=64704ABB4FEFAA7DE2A835AA53417B975E5F34A25881ABB17260F82DB732BA9EA35D47B412A6265E0B7EFA83BBF2B9C4B7EEFE03655E952E2995DCDF57182850F48028FF6A8B2394E68C3FA6FAC91AEA18268528F216A5780E746B28E32D05F25A665284890254FA7A831D6C12B48EB25715D4F08FAE10602DC08D50D32D9B2F6E0181B2D8D9DD4BE9D7E8841A38D791; user-key=3d404412-392b-4980-956d-337b1236a368; jwotest_product=98; mba_muid=1438699242760-365b910d29251d84a0; mt_xid=V2_52007VwMSVFRRUl4YTh9sVWELEQcIXAdGTEsbXRliBBQHQQtXWhdVHFsGZ1FHUQ5YVVsfeRpdBWMfElNBWVpLH0oSXQJsABViX2hRahtKH1wAYDMSVlw%3D; unpl=V2_ZzNtbRdTFBFzWxVSKxoOA2JWFVwSUEUddQ5PVysbWFFjV0FdclRCFXEURlVnGFQUZwEZXUpcQx1FCHZWfBBYA1czZ1xDVBdLKkxDDD4cXF4wC0sWESRzFXw4Q2R7GVoMbgMWWkVRcyVyOHZkeildNWY%3d; mt_subsite=||80%2C1444367959; cn=73; ipLocation=%u5317%u4EAC; areaId=1; ipLoc-djd=1-2901-4135-0; VC_INTEGRATION_JSESSIONID=ece149ca-17d0-4211-982d-37fa72249eb7; __jda=122270672.1178815667.1406816828.1444371360.1444381309.253; __jdb=122270672.1.1178815667|253.1444381309; __jdc=122270672; __jdv=122270672|fun.fanli.com|t_36857_|tuiguang|d5f57bb7a2c74d60a6791782a35e5eb1; __jdu=1178815667; _tp=MMAgxw75JQRWU%2FZJi67rRZNIi6zk1jOXIQyBLD3LtYk%3D; _pst=jd_4d3791da589fb; TrackID=16k-8RopJDW_wx-dgKyiDfv5ZFEi7qOlnGaECLHY848RPLWcQzPUdW9RQ1v0uIjvAW9XmW7Q283V3VwoxnXoCIvGrsAmK2CB0TTvMjswlz3o; pinId=0P1EO47V_CYe8GByxmhkXrV9-x-f3wj7; logining=1; unick=jd_huanme518; pin=jd_4d3791da589fb; thor=61837CE33D0FC9A2842214A6A13DB784108B19C88B342DE7B89B4098183B4D23C50DCE0C8B017CBE9E0B818158D475BDF5C8C37897124FC689432F123CDF09C51D56157D538F15DA6A0A6F7D735793A234331BE11B7963DDFFA755162413E5F555AD00034887FA43070FF44857F05EA6F1E7E96F1241C915D02FBD186AF5CA9F40DE76695F1782E169F6A229DCC5727CC080C5EEF2CC5DF486C6A3000BCE1BBA");
		post.setRequestHeader("Host", "vcp.jd.com");
		post.setRequestHeader("Origin", "http://vcp.jd.com");
		post.setRequestHeader("Pragma", "no-cache");
		post.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");
		post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		post.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		post.setRequestHeader("Referer", "http://vcp.jd.com/sub_procurement/procurement/initListPage");
		
		NameValuePair[] param = { 
				new NameValuePair("length", "100"),
				new NameValuePair("page", "1"),
				new NameValuePair("sidx", ""),
				new NameValuePair("sord", ""),
				new NameValuePair("stateList", "-1"),
				new NameValuePair("confirmStateList", "-1"),
				new NameValuePair("status", "1") };
		
		post.setRequestBody(param);
		post.releaseConnection();
		return post;
	}
	
	//采购订单查询
	private static String purchaseOrderURL = "http://vcp.jd.com/sub_procurement/procurement/initListPage";
	
	//退货单查询
	private static String refundOrderURL = "http://vcp.jd.com/sub_returns/returns/orderList";
	
	
	public static void main(String[] args) {
		JD renRen = new JD();
		renRen.printText();
	}
}